import { defineStore } from "pinia";
import { ref } from "vue";
import { getImageByRequestId } from "@/api/painting";
import { createImage } from "@/api/painting";
import { getToken } from "@/utils/auth";
import config from "@/config/config.json";
import { responseHandle } from "@/utils/request/requestHandle";
import Toast from "@vant/weapp/dist/toast/toast";

export const usePaintingStore = defineStore("painting-store", () => {

  // 文生图
  const textCreateImage = ref(uni.getStorageSync('textCreateImage') || {})
  // 设置文生图数据
  function setTextCreateImageFn(data) {
    textCreateImage.value = data;
    uni.setStorageSync('textCreateImage', data)
  }


  const isBuyModal = ref(false);

  // 图生图
  const pictureCreateImageObj = ref(uni.getStorageSync("pictureCreateImageObj") || {});

  // 生成背景图
  const generationBgc = ref(uni.getStorageSync("generationBgc") || {});
  // 设置生成背景图数据
  function setGenerationBgcFn(data) {
    generationBgc.value = data;
    uni.setStorageSync("generationBgc", data);
  }

  // 侧脸背景
  const faceBackground = ref(uni.getStorageSync("faceBackground") || {});
  // 设置生成背景图数据
  function setFaceBackgroundFn(data) {
    faceBackground.value = data;
    uni.setStorageSync("faceBackground", data);
  }



  // vip生成背景图
  const vipGenerationBgc = ref(uni.getStorageSync("vipGenerationBgc") || {});

  // 指令绘图
  const instructDraw = ref(uni.getStorageSync("instructDraw") || {});
  // 设置指令绘图数据
  function setinstructDrawFn(data) {
    instructDraw.value = data;
    uni.setStorageSync("instructDraw", data);
  }


  // 生成背景图V2
  const generationBgcV2 = ref(uni.getStorageSync("generationBgcV2") || {});
  // 设置生成背景图数据
  function setGenerationBgcV2Fn(data) {
    generationBgcV2.value = data;
    uni.setStorageSync("generationBgcV2", data);
  }


  // AI扩图
  const expansionPicture = ref(uni.getStorageSync("expansionPicture") || {})
  // 设置AI扩图数据
  function setExpansionPictureFn(data) {
    expansionPicture.value = data;
    uni.setStorageSync("expansionPicture", data);
  }

  // 局部重绘
  const localRedrawing = ref(uni.getStorageSync("localRedrawing") || {})
  // 设置局部重绘数据
  function setLocalRedrawingFn(data) {
    localRedrawing.value = data;
    uni.setStorageSync("localRedrawing", data);
  }


  // AI重绘背景
  const bgRedrawing = ref(uni.getStorageSync("bgRedrawing") || {})
  // 设置AI重绘背景数据
  function setBgRedrawingFn(data) {
    bgRedrawing.value = data;
    uni.setStorageSync("bgRedrawing", data);
  }

  // 清除绘图表单数据
  const clearImageObj = () => {
    uni.removeStorageSync("textCreateImage");
    textCreateImage.value = {};
    uni.removeStorageSync("pictureCreateImageObj");
    pictureCreateImageObj.value = {};
    uni.removeStorageSync("generationBgc");
    generationBgc.value = {};
    uni.removeStorageSync("generationBgcV2");
    generationBgcV2.value = {};
    uni.removeStorageSync("vipGenerationBgc");
    vipGenerationBgc.value = {};
    uni.removeStorageSync("expansionPicture");
    expansionPicture.value = {};
  };

  // 图片结果数据
  const imgResultObj = ref({});

  // 图片上传之后接口返回的原图在线地址
  const oriImage = ref("");

  /**
   * 抠图、图像消除、高清修复、图生图图片上传
   * @param canvas canvas实例
   * @returns url 可绘制到canvas上的图片临时地址
   */
  const imageUploadFile = ({
    url = "editImgUpload",
    name = "orgImg",
    tempFilePath,
    formData,
  }) => {
    console.log(formData, 12312313123);

    return new Promise(async (resolve, reject) => {
      const res = await uni.uploadFile({
        url: `${config.siteDomain}/api/AI_Image/${url}`,
        filePath: tempFilePath,
        name,
        header: {
          satoken: getToken(),
          "content-type": "multipart/form-data",
        },
        formData,
      });
      const result = JSON.parse(res.data);

      if (result.code == 200) {
        oriImage.value = result.data.orgImgUrl;
        return resolve(result.data.orgImgUrl);
      } else {
        reject(result);
        Toast.fail(result.message);
        responseHandle(result);
      }
    });
  };
  /**
   * 抠图、图像消除、高清修复、图生图图片上传
   * @param canvas canvas实例
   * @returns url 可绘制到canvas上的图片临时地址
   */
  const imageUploadMaskFile = async (tempFilePath, formData) => {
    const res = await uni.uploadFile({
      url: `${config.siteDomain}/api/AI_Image/maskImgUpload`,
      filePath: tempFilePath,
      name: "maskImg",
      header: {
        satoken: getToken(),
        "content-type": "multipart/form-data",
      },
      formData,
    });
    const result = JSON.parse(res.data);

    if (result.code == 200) {
      oriImage.value = result.data.maskImgUrl;
      return result.data.maskImgUrl;
    } else {
      res.data = JSON.parse(res.data);
      responseHandle(res);
    }
  };

  // canvas保存图片
  const canvasSaveImgFn = async (canvas) => {
    try {
      const res = await uni.canvasToTempFilePath({
        canvas,
      });
      await uni.saveImageToPhotosAlbum({ filePath: res.tempFilePath });
      Toast.success("保存成功");
    } catch (error) {
      Toast.clear();
    }
  };

  // 网络地址保存图片
  const urlSaveImgFn = async (path) => {
    try {
      if (Array.isArray(path)) {
        path.forEach(async (item) => {
          let res = await uni.downloadFile({
            url: item,
            header: {
              Satoken: getToken(),
            },
          });

          await uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
          });
        });
        Toast.success("保存成功");
      } else {
        const res = await uni.downloadFile({
          url: path,
          header: {
            Satoken: getToken(),
          },
        });
        await uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
        });
        Toast.success("保存成功");
      }
    } catch (error) {
      Toast.clear();
    }
  };

  // 保存图片
  const saveImg = async (val) => {
    Toast.loading({
      message: "下载中...",
      forbidClick: true,
      duration: 0,
    });
    val.canvas ? canvasSaveImgFn(val.canvas) : urlSaveImgFn(val.path);
  };

  // 判断用户是否授权
  /**
   *
   * @param {
   * canvas,
   * path
   * }
   */
  const accredit = async (value) => {
    // 获取已经获得的权限列表
    const res = await uni.getSetting();
    // 已获得存储相册授权
    if (res.authSetting["scope.writePhotosAlbum"]) {
      // 直接下载图片文件到本地
      saveImg(value);
    } else if (res.authSetting["scope.writePhotosAlbum"] === undefined) {
      // 未获得存储相册授权
      uni.authorize({
        scope: "scope.writePhotosAlbum",
        success(res) {
          saveImg(value);
        },
      });
    } else {
      uni.openSetting();
    }
  };

  // 绘制图片方法
  const createImageFn = async () => {
    const res = await createImage(textCreateImageObj.value);
    textCreateImageObj.value.taskId = res.data.taskId;
  };

  return {
    isBuyModal,
    textCreateImage,
    setTextCreateImageFn,
    pictureCreateImageObj,
    imgResultObj,
    expansionPicture,
    setExpansionPictureFn,
    createImageFn,
    imageUploadFile,
    imageUploadMaskFile,
    accredit,
    oriImage,
    urlSaveImgFn,
    clearImageObj,
    generationBgc,
    setGenerationBgcFn,
    faceBackground,
    setFaceBackgroundFn,
    generationBgcV2,
    setGenerationBgcV2Fn,
    vipGenerationBgc,
    instructDraw,
    setinstructDrawFn,
    localRedrawing,
    setLocalRedrawingFn,
    bgRedrawing,
    setBgRedrawingFn,
  };
});
